import json
import logging

from django.db.models import Q
from django.shortcuts import render

import settings

from blueapps.core.exceptions import DatabaseError
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from design import models
from design.models import Content, People
from design.utils.user import identify_user

# Create your views here.


logger = logging.getLogger("root")


# def upload(request):
#     error = ''
#     if request.method == 'POST':
#         img = request.FILES.get('img')
#         pic_name = img.name
#         if pic_name.split('.')[-1] == 'mp4':
#             error = '暂不支持上传此格式图片！！！'
#         else:
#             models.People.objects.create(img_name=pic_name, img=img)
#             return redirect('show')
#     return render(request, 'upload.html', locals())
#
#
# def show(request):
#     all_images = models.People.objects.all()
#     # for i in all_images:
#     #     print(i.img)
#     # return render(request, 'show.html', locals())
#     return JsonResponse(
#         {"result": False, "code": 200, "data": {}, "message": ""},
#         json_dumps_params={"ensure_ascii": False}
#     )


# def img_people(request):
#     if request.method == 'POST':
#         # 前端ajax请求，将图片对象、图片名称传递到了后台的views.py中；
#         img = request.FILES.get('img_file')
#         # 获取数据库head_img字段的值，并切割成列表。
#         # ['2018', '10', 'h2.png']
#         path = request.user.head_img.url.split('/')
#         # 将列表的最后一个元素图片名称，替换成新的图片名称
#         path[-1] = request.POST.get('img_name')
#         # 再将列表合成一个字符串
#         path = '/'.join(path)
#
#         url = settings.MEDIA_ROOT + '/' + path
#
#         # 将ajax传过来的图片写入到本地/static/images/....目录下。
#         with open(url, 'wb') as f:
#             for chunk in img.chunks():
#                 f.write(chunk)
#
#         # 以上步骤实现了图片的后台保存，还需要修改当前用户数据库中的头像路径。
#         request.user.head_img = path
#         request.user.save()
#
#         return JsonResponse(
#             {"result": False, "code": 200, "data": {}, "message": "上传成功"},
#             json_dumps_params={"ensure_ascii": False}
#         )


@csrf_exempt
def create_user(request):
    req = json.loads(request.body)
    student_id = req.pop("student_id")
    nick_name = req.pop("nick_name")
    visible_information = True
    questions_number = 0
    answers_number = 0

    exits, judge = People.objects.get_or_create(student_id=student_id, nick_name=nick_name,
                                                visible_information=visible_information,
                                                questions_number=questions_number, answers_number=answers_number)

    if judge is True:
        return JsonResponse(
            {"result": False, "code": 200, "data": {}, "message": "创建成功"},
            json_dumps_params={"ensure_ascii": False}
        )
    else:
        return JsonResponse(
            {"result": False, "code": 400, "data": {}, "message": "已有该账号"},
            json_dumps_params={"ensure_ascii": False}
        )


@csrf_exempt
def get_user_list(request):
    """
    获取用户信息
    """
    if request.method == "GET":
        student_id = request.GET.get("student_id")
        member = models.People.objects.get(student_id=student_id)
        return JsonResponse(
            {
                "result": True,
                "code": 200,
                "data": {
                    "id": member.id,
                    "nick_name": member.nick_name,
                    "user_name": member.user_name,
                    "student_id": member.student_id,
                    "college": member.college,
                    "major": member.major,
                    "grade": member.grade,
                    "gender": member.gender,
                    "birthday": member.birthday,
                    "visible_information": member.visible_information,
                    "personal_signature": member.personal_signature,
                    "qq_number": member.qq_number,
                    "wechat_number": member.wechat_number,
                    "questions_number": member.questions_number,
                    "answers_number": member.answers_number,
                },
                "message": "获取用户信息成功",
            },
            json_dumps_params={"ensure_ascii": False}
        )
    else:
        return JsonResponse(
            {"result": False, "code": 501, "data": {}, "message": "请求失败"},
            json_dumps_params={"ensure_ascii": False}
        )


@csrf_exempt
def update_user_info(request):
    """
    修改用户信息
    """
    if request.method == "PUT":
        student_id = request.GET.get("student_id")
        print(student_id)
        req = json.loads(request.body)
        qq_number = req.pop("qq_number")
        wechat_number = req.pop("wechat_number")
        visible_information = req.pop("visible_information")
        personal_signature = req.pop("personal_signature")
        if not student_id or type(visible_information) is not bool:
            return JsonResponse(
                {
                    "result": False,
                    "message": "修改失败！学号或输入信息错误",
                    "code": 400,
                    "data": [],
                },
                json_dumps_params={"ensure_ascii": False},
            )
        try:
            people = models.People.objects.get(student_id=student_id)
            people.qq_number = qq_number
            people.wechat_number = wechat_number
            people.visible_information = visible_information
            people.personal_signature = personal_signature
            people.save()
            return JsonResponse(
                {"result": True, "message": "修改成功", "code": 200, "data": []},
                json_dumps_params={"ensure_ascii": False},
            )
        except DatabaseError as e:
            logger.exception(e)
            return JsonResponse(
                {
                    "result": False,
                    "message": "修改失败",
                    "code": 412,
                    "data": [],
                },
                json_dumps_params={"ensure_ascii": False},
            )
    else:
        return JsonResponse(
            {"result": False, "code": 501, "data": {}, "message": "请求失败"},
            json_dumps_params={"ensure_ascii": False}
        )


@csrf_exempt
def verify_school_user(request):
    """
    功能：通过学分制的账号密码, 进行验证, 并绑定用户
    输入：request头中带有student_id,password
    返回：认证成功： result: True; data: user_id
         认证失败： result: False; data: []; message：错误信息
    """
    if request.method == "POST":
        try:
            body = json.loads(request.body)
            username = request.GET.get("student_id")
            password = body.get("password")

            if username == "test":
                member = models.People.objects.get(student_id=request.user.username)
                member.save()
                return JsonResponse(
                    {
                        "result": True,
                        "code": 201,
                        "message": "test认证成功",
                        "data": {"user_id": member.id},
                    }
                )

            result, user_info, message = identify_user(
                username=str(username), password=str(password)
            )
            if result:
                user, _ = models.People.objects.get_or_create(student_id=username)
                kwargs = {
                    "class_number": user_info["user_name"],  # 学号
                    "name": user_info["user_real_name"],  # 姓名
                    "professional_class": user_info["user_major"],  # 专业
                    "classroom": user_info["user_class"],  # 班级
                    "gender": models.People.Gender.MAN
                    if user_info["user_sex"] == "男"
                    else models.People.Gender.WOMAN,
                    "college": user_info["user_college"],  # 学院
                }
                if request.is_wechat():
                    kwargs["username"] = "{}X".format(user_info["user_name"])
                    kwargs["openid"] = request.user.openid

                for attr_name, attr_value in kwargs.items():
                    setattr(user, attr_name, attr_value)

                user.save()
                data = {
                    "result": True,
                    "message": message,
                    "code": 201,
                    "data": {},
                }
                return JsonResponse(data)
            else:
                data = {"result": False, "message": message, "data": []}
                return JsonResponse(data)
        except Exception as e:
            data = {"result": False, "message": e, "code": 500, "data": []}  # 后端出错
            return JsonResponse(data)


@csrf_exempt
def get_contents_by_label(request):
    """
    通过标签获取内容
    """
    # 从请求的 GET 参数中获取 'label'
    label = request.GET.get('label')
    # 使用 ORM 获取所有 content_label 为 'label' 的内容
    contents = Content.objects.filter(content_label=label)
    # 将内容转换为字典列表
    data = [
        {'id': c.id, 'content_type': c.content_type, 'content_label': c.content_label, 'content_title': c.content_title,
         'content': c.content, 'liked_number': c.liked_number, 'favorite_number': c.favorite_number,
         'content_create_time': c.content_create_time, 'content_create_people': c.content_create_people} for c in
        contents]
    # 返回 JSON 格式的响应
    return JsonResponse(
        {"result": True, "message": "获取成功", "code": 200, "data": data},
        json_dumps_params={"ensure_ascii": False},
    )


@csrf_exempt
def get_contents_by_people(request):
    """
    通过创建人获取内容
    """
    # 从请求的 GET 参数中获取 'student_id'
    student_id = request.GET.get('student_id')
    # 使用 ORM 获取所有 content_label 为 'label' 的内容
    contents = Content.objects.filter(content_create_people=student_id)
    # 将内容转换为字典列表
    data = [
        {'id': c.id, 'content_type': c.content_type, 'content_label': c.content_label, 'content_title': c.content_title,
         'content': c.content, 'liked_number': c.liked_number, 'favorite_number': c.favorite_number,
         'content_create_time': c.content_create_time, 'content_create_people': c.content_create_people} for c in
        contents]
    # 返回 JSON 格式的响应
    return JsonResponse(
        {"result": True, "message": "获取成功", "code": 200, "data": data},
        json_dumps_params={"ensure_ascii": False},
    )


@csrf_exempt
def search_contents(request):
    """
    通过搜索获取内容
    """
    # 从请求的 GET 参数中获取 'search'
    body = json.loads(request.body)
    search = body.get("search")
    # 使用 ORM 获取内容标题或内容中包含 'search' 的最匹配的内容
    content = Content.objects.filter(Q(content_title__contains=search) | Q(content__contains=search)).order_by(
        '-liked_number', '-favorite_number').first()
    # 将内容转换为字典
    data = {'id': content.id, 'content_type': content.content_type, 'content_label': content.content_label,
            'content_title': content.content_title, 'content': content.content, 'liked_number': content.liked_number,
            'favorite_number': content.favorite_number, 'content_create_time': content.content_create_time,
            'content_create_people': content.content_create_people}
    # 返回 JSON 格式的响应
    return JsonResponse(
        {"result": True, "message": "获取成功", "code": 200, "data": data},
        json_dumps_params={"ensure_ascii": False},
    )


@csrf_exempt
def publish_content(request):
    """
    发布内容
    """
    # 从请求的 POST 参数中获取内容表相关信息
    body = json.loads(request.body)
    content_type = body.get('content_type')
    content_label = body.get('content_label')
    content_title = body.get('content_title')
    content = body.get('content')
    content_create_people = body.get('content_create_people')
    # 使用 ORM 创建一条新的内容
    try:
        content = Content.objects.create(content_type=content_type, content_label=content_label,
                                         favorite_number=0, liked_number=0,
                                         content_title=content_title, content=content, content_create_time=None,
                                         content_create_people=content_create_people)
    except DatabaseError as e:
        logger.exception(e)
        return JsonResponse(
            {"result": True, "message": "发布失败", "code": 401, "data": []},
            json_dumps_params={"ensure_ascii": False},
        )
    return JsonResponse(
        {"result": True, "message": "发布成功", "code": 200, "data": []},
        json_dumps_params={"ensure_ascii": False},
    )


@csrf_exempt
def get_question_content_personal(request):
    """
    获取个人问题
    """
    if request.method == "GET":
        content_list = []
        student_id = request.GET.get("student_id")
        contents = Content.objects.filter(content_type="QUESTION", content_create_people=student_id)
        for content in contents:
            content_list.append({
                'id': content.id, 'content_type': content.content_type, 'content_label': content.content_label,
                'content_title': content.content_title, 'content': content.content,
                'liked_number': content.liked_number,
                'favorite_number': content.favorite_number, 'content_create_time': content.content_create_time,
                'content_create_people': content.content_create_people
            })
        return JsonResponse(
            {"result": True, "message": "获取成功", "code": 200, "data": content_list},
            json_dumps_params={"ensure_ascii": False},
        )


@csrf_exempt
def get_answer_content_personal(request):
    """
    获取个人回答
    """
    if request.method == "GET":
        content_list = []
        student_id = request.GET.get("student_id")
        contents = Content.objects.filter(content_type="ANSWER", content_create_people=student_id)
        for content in contents:
            content_list.append({
                'id': content.id, 'content_type': content.content_type, 'content_label': content.content_label,
                'content_title': content.content_title, 'content': content.content,
                'liked_number': content.liked_number,
                'favorite_number': content.favorite_number, 'content_create_time': content.content_create_time,
                'content_create_people': content.content_create_people
            })
        return JsonResponse(
            {"result": True, "message": "获取成功", "code": 200, "data": content_list},
            json_dumps_params={"ensure_ascii": False},
        )


@csrf_exempt
def content_like(request):
    if request.method == "GET":
        student_id = request.GET.get("student_id")
        content_list = []
        peoples = People.objects.filter(student_id=student_id)
        for people in peoples:
            contents = people.like_content.all()
            for content in contents:
                content_list.append({
                    'id': content.id, 'content_type': content.content_type, 'content_label': content.content_label,
                    'content_title': content.content_title, 'content': content.content,
                    'liked_number': content.liked_number,
                    'favorite_number': content.favorite_number, 'content_create_time': content.content_create_time,
                    'content_create_people': content.content_create_people
                })
            return JsonResponse(
                {"result": True, "message": "获取成功", "code": 200, "data": content_list},
                json_dumps_params={"ensure_ascii": False},
            )
    if request.method == "PUT":
        student_id = request.GET.get("student_id")
        content_id = request.GET.get("content_id")
        peoples = People.objects.filter(student_id=student_id)
        for people in peoples:
            people.like_content.set([people.id, content_id])
        return JsonResponse(
            {"result": True, "message": "更新成功", "code": 200, "data": []},
            json_dumps_params={"ensure_ascii": False},
        )
    return JsonResponse(
        {"result": True, "message": "请求方式错误", "code": 401, "data": []},
        json_dumps_params={"ensure_ascii": False},
    )


@csrf_exempt
def content_favorite(request):
    if request.method == "GET":
        student_id = request.GET.get("student_id")
        content_list = []
        peoples = People.objects.filter(student_id=student_id)
        for people in peoples:
            contents = people.favorite_content.all()
            for content in contents:
                content_list.append({
                    'id': content.id, 'content_type': content.content_type, 'content_label': content.content_label,
                    'content_title': content.content_title, 'content': content.content,
                    'liked_number': content.liked_number,
                    'favorite_number': content.favorite_number, 'content_create_time': content.content_create_time,
                    'content_create_people': content.content_create_people
                })
            return JsonResponse(
                {"result": True, "message": "获取成功", "code": 200, "data": content_list},
                json_dumps_params={"ensure_ascii": False},
            )
    if request.method == "PUT":
        student_id = request.GET.get("student_id")
        content_id = request.GET.get("content_id")
        peoples = People.objects.filter(student_id=student_id)
        for people in peoples:
            people.favorite_content.set([people.id, content_id])
        return JsonResponse(
            {"result": True, "message": "更新成功", "code": 200, "data": []},
            json_dumps_params={"ensure_ascii": False},
        )
    return JsonResponse(
        {"result": True, "message": "请求方式错误", "code": 401, "data": []},
        json_dumps_params={"ensure_ascii": False},
    )


def home(request):
    return render(request, "index.html")
